package com.kfm.servlet;

import com.kfm.db.DBUtils;
import com.kfm.model.AccountModel;
import com.wf.captcha.utils.CaptchaUtil;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Object msg = req.getSession().getAttribute("msg");
        if (msg != null ){
            req.setAttribute("success", msg);
            req.getSession().removeAttribute("msg");
        }
        req.getRequestDispatcher("index.jsp").forward(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取请求参数
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String captcha = req.getParameter("captcha");
        // 验证码校验
        if (!CaptchaUtil.ver(captcha, req)){
            // 验证码错误
            req.setAttribute("msg", "验证码错误");
            req.getRequestDispatcher("index.jsp").forward(req, resp);
            return;
        }
        // 验证码正确, 清除验证码
        CaptchaUtil.clear(req);

        // 验证用户名和密码
        String sql = "select id, phone, type, point, name, create_time, money from account where phone = ? and password = ?";

        DBUtils<AccountModel> dbUtils = new DBUtils<>(1);

        AccountModel accountModel = dbUtils.selectOne(sql, AccountModel.class, username, password);

        if (accountModel != null){
            // 登录成功, 重定向到首页
            // 将用户信息保存到 session 中
            HttpSession session = req.getSession();
            session.setAttribute("user", accountModel);

            ServletContext servletContext = getServletContext();
            // 保存在线用户
            Object online = servletContext.getAttribute("online");
            resp.sendRedirect("index");
            if (online == null) {
                Map<String, HttpSession> map = new HashMap<>();
                map.put(session.getId(), session);
                servletContext.setAttribute("online", map);
            } else {
                if (online instanceof Map map){
                    map.put(session.getId(), session);
                }
            }
        }else {
            // 登录失败
            req.setAttribute("msg", "用户名或密码错误");
            req.getRequestDispatcher("index.jsp").forward(req, resp);
        }

    }
}
